package com.spzhao.qrcodescaner;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.WriterException;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import beans.QrMessage;
import utils.QrCodeGen;
import utils.QrEdit;

public class QrCode_detail extends AppCompatActivity implements View.OnClickListener {

    private JSONObject data;
    private TextView name, time, qrText;
    private ImageView infoImage, genImage;
    private QrCodeGen qrCodeGen;
    private Bitmap qrBitmap;
    private ImageView editImg, copyImg, shareImg;
    private ImageButton editBtn, copyBtn, shareBtn;
    private Boolean isNeedUpdate;
    private Integer resultCode;
    private QrMessage qrMessageBean;
    private static String TAG = "qr detail activity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrcode_detail);

        isNeedUpdate = false;

        try {
            data = new JSONObject(getIntent().getStringExtra("data"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        bindViews();
        bindOption();
    }

    /**
     * 绑定布局中的控件
     * <p>初始化二维码</p>
     */
    private void bindViews() {
        name = (TextView) findViewById(R.id.detail_name);
        time = (TextView) findViewById(R.id.detail_time);
        qrText = (TextView) findViewById(R.id.qrText);

        try {
            name.setText(data.getString("name"));
            qrText.setText(data.getString("text"));
            time.setText("创建于" + data.getString("time"));

            resultCode = data.getInt("code");
            genQrImage(data.getString("text"));

            qrMessageBean = new QrMessage(
                    data.getString("name"),
                    data.getString("text"),
                    data.getString("time"),
                    data.getString("color")
            );

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成二维码方法
     *
     * @param text 二维码的内容
     */
    public void genQrImage(String text) {
        if (qrCodeGen == null) {
            qrCodeGen = new QrCodeGen();
        }
        try {
            qrBitmap = qrCodeGen.Create2DCode(text);
        } catch (WriterException e) {
            e.printStackTrace();
        }

//        infoImage = (ImageView) findViewById(R.id.infoImage);
        genImage = (ImageView) findViewById(R.id.qrImage);

        if (qrBitmap != null) {
            genImage.setImageBitmap(qrBitmap);
        } else {
            Toast.makeText(this, "生成图片失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 二维码操作绑定
     */
    private void bindOption() {
        editBtn = (ImageButton) findViewById(R.id.imageBtnEdit);
        editBtn.setOnClickListener(this);

        editImg = (ImageView) findViewById(R.id.imageVCopy);
        editImg.setOnClickListener(this);

        shareImg = (ImageView) findViewById(R.id.imageVShare);
        shareImg.setOnClickListener(this);
    }

    /**
     * 显示对话框
     * 新建一个类，便于其他页面进行二维码编辑和添加
     */
    private void showDialog() {
        final LinearLayout edit_dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.edit_dialog, null);
        final QrEdit qrEdit = new QrEdit(this, edit_dialog) {
            /**
             * 在这里进行自定义对话框的数据绑定
             */
            @Override
            public void bindView() {
                EditText edit_name = (EditText) edit_dialog.findViewById(R.id.edit_name);
                EditText edit_text = (EditText) edit_dialog.findViewById(R.id.edit_text);

                edit_name.setText(name.getText());

                edit_text.setText(qrText.getText());
            }

            /**
             * 实现点击确定按钮后的方法
             */
            @Override
            public void sureClick() {
                EditText edit_name = (EditText) edit_dialog.findViewById(R.id.edit_name);
                EditText edit_text = (EditText) edit_dialog.findViewById(R.id.edit_text);


                Log.i(" abc ", String.valueOf(qrText.getText()) + " == " + String.valueOf(edit_text.getText()));
                /**
                 * 判断是否修改了二维码内容，如果修改了，就重新生成二维码
                 * TODO 保存新的二维码内容到SP中
                 * TODO 询问用户是否需要保存新的二维码
                 * TODO 保存了二维码后返回到主页面需要刷新页面
                 */
                if (!String.valueOf(qrText.getText()).equals(String.valueOf(edit_text.getText()))) {
                    genQrImage(String.valueOf(edit_text.getText()));
                    qrText.setText(edit_text.getText());
                    ShowSaveAlert(String.valueOf(edit_name.getText()), String.valueOf(edit_text.getText()));
//                    saveToSP(String.valueOf(edit_name.getText()), String.valueOf(edit_text.getText()));
                }
                if (!String.valueOf(name.getText()).equals(String.valueOf(edit_name.getText()))
                        && String.valueOf(qrText.getText()).equals(String.valueOf(edit_text.getText()))) {
                    saveToSP(String.valueOf(edit_name.getText()), String.valueOf(edit_text.getText()));
                }
                name.setText(edit_name.getText());
            }
        };
        qrEdit.showDialog();
    }

    private void ShowSaveAlert(final String name, final String text) {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("提示");
        alert.setMessage("是否保存");
        alert.setNegativeButton("否", null);
        alert.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                saveToSP(name, text);
            }
        });
        alert.show();
    }

    private void saveToSP(final String name, final String text) {

        qrMessageBean.setName(name);
        qrMessageBean.setText(text);
        qrMessageBean.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        try {
            qrMessageBean.saveOrUpdate();
            Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
            // 设置更新的状态
            isNeedUpdate = true;
            setResult();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void shareToBrw (String text) {
        //从其他浏览器打开
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri content_url = Uri.parse(text);
        Log.i(TAG,"uri " + content_url);
        intent.setData(content_url);
        startActivity(Intent.createChooser(intent, "请选择浏览器"));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imageBtnEdit:
                Log.i(TAG, "edit image click");
                showDialog();
                break;
            case R.id.imageVCopy:
                qrMessageBean.copyToClip();
                break;
            case R.id.imageVShare:
                shareToBrw(String.valueOf(qrText.getText()));
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void setResult () {
        String result = "true";
        Intent intent = new Intent();
        intent.putExtra("result",result);

        setResult(resultCode,intent);

        Log.i(TAG,"set result");
    }
}
